const Koa = require('koa')
const {koaBody} = require('koa-body')
const app = new Koa()

const logger = require('koa-logger')
const bodyparser = require('koa-bodyparser')
const Router = require('@koa/router')
const source = require('koa-static');
//导入cors包
const cors = require('koa2-cors')
const fs = require("fs");
const {baseFun} = require("./comHandler");
const toolBase = require('../tool/toolBase');
const {CROS_DOMAIN, APP_PORT} = require('../config/config.default')

app.use(koaBody())
// app.on('error', errHandler)

//跨域配置
app.use(cors({
    origin: function (ctx) { //ctx.url 设置允许来自指定域名请求
        // console.log(ctx);
        let arr = CROS_DOMAIN.split(';');
        let org = arr.indexOf(ctx.header.origin);
        let r = org > -1 ? arr[org] : null;//可访问的域名
        // console.log(r)
        return r;
    },
    maxAge: 60 * 60 * 10, //指定本次预检请求的有效期，单位为秒。
    credentials: false, //是否允许发送Cookie
    allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], //设置所允许的HTTP请求方法
    allowHeaders: ['*'], //设置服务器支持的所有头信息字段
    // exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'] //设置获取其他自定义字段
}));

// middlewares
app.use(bodyparser({
    enableTypes: ['json', 'form', 'text']
}))
app.use(logger());
app.use(source(__dirname + '/public'))
//全局异常
app.use(baseFun);
//后台异常日志输出
app.on('error', (err, ctx) => {
    // 如果说，错误提前被catch处里了，那么不会出发error事件
    //这里可以错误记录进文件
    console.error(err);//打印错误
})
//首页
const router = new Router({prefix: null})
router.get('/', async (ctx, next) => {
    ctx.type = 'html';
    let index = fs.readFileSync(process.cwd() + '/src/app/index.html', 'utf8');//启动js为根
    ctx.body = index;
})
//测试链接
router.post('/test', async (ctx, next) => {
    ctx.body = toolBase.resSuccess("欢迎进入咕咕咕系统！");
})
app.use(router.routes(), router.allowedMethods())
//异常


//路由注册
const routerUser = require('../router/user.route')
const routerRecord = require('../router/record.route')
const routerCommon = require('../router/common.route');
app.use(routerUser.routes()).use(routerUser.allowedMethods())
app.use(routerRecord.routes()).use(routerRecord.allowedMethods())
app.use(routerCommon.routes()).use(routerCommon.allowedMethods());

app.listen(APP_PORT, () => {
    console.log(new Date().toLocaleString() + ` 服务已启动, http://localhost:${APP_PORT}`)
})
module.exports = app